var identifyQueryHandler = null;

/**
 * 点击查询、穿透查询
 * @param {*} type  1：点击  2：穿透
 */
function identifyQuery(type, copy) {
    RemoveAllLayers();
    if (identifyQueryHandler) {
        identifyQueryHandler.destroy();
    }
    var tooltip = new GlobeTooltip(viewer.container);
    var cartesian = null;
    identifyQueryHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    var ellipsoid = viewer.scene.globe.ellipsoid;
    identifyQueryHandler.setInputAction(function(movement) {
        //通过指定的椭球或者地图对应的坐标系，将鼠标的二维坐标转换为对应椭球体三维坐标
        cartesian = getPickPositionGlobe(movement.position);
        if (cartesian) {
            //将笛卡尔坐标转换为地理坐标
            var cartographic = ellipsoid.cartesianToCartographic(cartesian);
            //将弧度转为度的十进制度表示
            var longitudeString = Cesium.Math.toDegrees(cartographic.longitude);
            var latitudeString = Cesium.Math.toDegrees(cartographic.latitude);
            var point = longitudeString + ',' + latitudeString;
            queryLayerInfoByPoint(point, type, null, copy);
            tooltip.setVisible(false);
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    //鼠标移动
    identifyQueryHandler.setInputAction(function(event) {
        var wp = event.endPosition;
        if (!Cesium.defined(wp)) {
            return;
        }
        if (cartesian == null) {
            tooltip.showAt(wp, "<p>单击选择位置</p>");
        }
        var position = getPickPositionGlobe(wp);
        if (!Cesium.defined(position)) {
            return;
        }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    identifyQueryHandler.setInputAction(function(movement) {
        removeAllEntities();
        identifyClear();
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
}

/**
 * 通过点选来选择并获取图层对象
 * @param {*} point  String : x,y
              polyline String x,y x,y x,y ...
              polygon  String x,y x,y x,y ...
 * @param {*} type  1：点击  2：穿透  3:框选
 * 将查询结果统一转换成geojson数据格式
 */
function queryLayerInfoByPoint(point, type, layerIds, copy) {
    $.ajaxSettings.async = false;
    var result;
    var results = [];

    if (!layerIds) {
        layerIds = [];
        for (var attr in cesium.layer3DList) {
            var layerItem = cesium.layer3DList[attr];
            // if (layerItem["NAME"] && layerItem["SERVICETYPE"] != sw_servicetype.sw_terrain && layerItem["SERVICETYPE"] != sw_servicetype.sw_oblique && layerItem["SOURCE"] != sw_source.sw_mongodb) {
            if (layerItem["NAME"] && layerItem["SERVICETYPE"] != sw_servicetype.sw_terrain && layerItem["SOURCE"] != sw_source.sw_mongodb) {
                layerIds.push(attr);
            }
        }
    }else if(typeof(layerIds) == "string"){
        layerIds = [layerIds];
    }
    for (var i = 0 ; i < layerIds.length ; i++) {
        var layerItem = cesium.layer3DList[layerIds[i]];
        var queryUrl = "";
        var params = {};
        var layerUrl = layerItem["URL"];
        switch (layerItem["SERVICETYPE"]) {
            case sw_servicetype.sw_tile://tile
                switch (layerItem["SOURCE"]) {
                    case sw_source.sw_arcgis://arcgis
                    case sw_source.sw_arcgistile://arcgis
                        queryUrl = layerUrl + '/identify';
                        params = {
                            sr: 4326,
                            layers: 'visible',
                            tolerance: 3,
                            mapExtent: GetViewExtent().toString(),
                            imageDisplay: viewer.scene.canvas.width + ',' + viewer.scene.canvas.height + ',96',
                            returnGeometry: true,
                            returnFieldName: true,
                            f: 'json'
                        }
                        if (type == 1 || type == 2) {//point
                            params["geometry"] = encodeURIComponent(JSON.stringify({ "x": parseFloat(point.split(",")[0]), "y": parseFloat(point.split(",")[1]) }));
                            params["geometryType"] = 'esriGeometryPoint'
                        } else if (type == 3) {//polygon
                            params["geometry"] = encodeURIComponent(JSON.stringify({
                                "rings": [pointStringsToArrayForQuery(point)]
                            })) ;
                            params["geometryType"] = 'esriGeometryPolygon'
                        } else if (type == 4) {//polgline
                            params["geometry"] = encodeURIComponent(JSON.stringify({
                                "paths": [pointStringsToArrayForQuery(point)]
                            })) ;
                            params["geometryType"] = 'esriGeometryPolyline'
                        }
                        break;
                    case sw_source.sw_wms:
                        if (type == 1 || type == 2) {
                            queryUrl = layerUrl + "/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=" + layerInfo.layerid + "&outputFormat=application/json&srsName=" + (layerInfo.srsName ? layerInfo.srsName : "EPSG:3857") + "&filter=<Filter xmlns='http://www.opengis.net/ogc' xmlns:gml='http://www.opengis.net/gml'><Intersects><PropertyName>the_geom</PropertyName><gml:Point srsName='EPSG:4326'><gml:coordinates>" + point + "</gml:coordinates></gml:Point></Intersects></Filter>";
                        } else if (type == 3) {
                            queryUrl = layerUrl + "/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=" + layerInfo.layerid + "&outputFormat=application/json&srsName=" + (layerInfo.srsName ? layerInfo.srsName : "EPSG:3857") + "&filter=<Filter xmlns='http://www.opengis.net/ogc' xmlns:gml='http://www.opengis.net/gml'><Intersects><PropertyName>the_geom</PropertyName><gml:Polygon srsName='EPSG:4326'><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>" + point + "</gml:coordinates> </gml:LinearRing> </gml:outerBoundaryIs> </gml:Polygon></Intersects></Filter>";
                        } else if (type == 4) {
                            queryUrl = layerUrl + "/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=" + layerInfo.layerid + "&outputFormat=application/json&srsName=" + (layerInfo.srsName ? layerInfo.srsName : "EPSG:3857") + "&filter=<Filter xmlns='http://www.opengis.net/ogc' xmlns:gml='http://www.opengis.net/gml'><Intersects><PropertyName>the_geom</PropertyName><gml:Polyline srsName='EPSG:4326'><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>" + point + "</gml:coordinates> </gml:LinearRing> </gml:outerBoundaryIs> </gml:Polyline></Intersects></Filter>";
                        }
                        break;
                    default:
                        break;
                }
                break;
            case sw_servicetype.vector://vector

                break;
            case sw_servicetype.sw_oblique:
                queryUrl = 'http://192.168.100.111:6080/arcgis/rest/services/basepordos/CKQZY/MapServer/identify';
                params = {
                    sr: 4326,
                    layers: 'visible',
                    tolerance: 3,
                    mapExtent: GetViewExtent().toString(),
                    imageDisplay: viewer.scene.canvas.width + ',' + viewer.scene.canvas.height + ',96',
                    returnGeometry: true,
                    returnFieldName: true,
                    f: 'json'
                }
                //TODO encodeURIComponent
                if (type == 1 || type == 2) {//point
                    params["geometry"] = encodeURIComponent(JSON.stringify({ "x": parseFloat(point.split(",")[0]), "y": parseFloat(point.split(",")[1]) })) ;
                    params["geometryType"] = 'esriGeometryPoint'
                } else if (type == 3) {//polygon
                    params["geometry"] = encodeURIComponent(JSON.stringify({
                        "rings": [pointStringsToArrayForQuery(point)]
                    })) ;
                    params["geometryType"] = 'esriGeometryPolygon'
                } else if (type == 4) {//polgline
                    params["geometry"] = encodeURIComponent(JSON.stringify({
                        "paths": [pointStringsToArrayForQuery(point)]
                    })) ;
                    params["geometryType"] = 'esriGeometryPolyline'
                }
                break;
            default:
                break;

        }
        $.get(queryUrl, params, function (data, status) {
            if(typeof(data) === "string"){
                data = JSON.parse(data)
            }
            result = handleToGeojson(data.results, "arcgis");
        });
        if (result && result.features.length > 0) {
            results.push({
                name: layerItem["NAME"],
                id: layerIds[i],
                data: result
            });
        }
    }
    if (results.length > 0) {
        changeFeaturesForTabTable(results, copy);
    } else {
        removeAllEntities();
        $("#queryResult").hide();
        showMsgLayer("未查询到数据！");
    }
}

//拉框查询
function rectangleIdentifyQuery() {
    removeAllEntities();
    var tooltip = new GlobeTooltip(viewer.container);
    var drawRectanglePoints = [];
    var activeShapePoints = [];
    var activeShape;
    var floatingPoint;
    if (identifyQueryHandler) {
        identifyQueryHandler.destroy();
    }
    identifyQueryHandler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);

    //双击鼠标左键清除默认事件
    viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
    //绘制点
    function createPoint(worldPosition) {
        drawRectanglePoints.push(worldPosition);
        var point = viewer.entities.add({
            position: worldPosition,
            point: {
                color: Cesium.Color.WHITE,
                pixelSize: 5,
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            }
        });
        return point;
    }
    var drawingMode = 'rectangle';

    function drawShape(positionData) {
        //当positionData为数组时绘制最终图，如果为function则绘制动态图
        var arr = typeof positionData.getValue === 'function' ? positionData.getValue(0) : positionData;
        var shape = viewer.entities.add({
            name: 'Blue translucent, rotated, and extruded ellipse with outline',
            rectangle: {
                coordinates: new Cesium.CallbackProperty(function() {
                    var obj = Cesium.Rectangle.fromCartesianArray(arr);
                    return obj;
                }, false),
                material: Cesium.Color.RED.withAlpha(0.5)
            }
        });
        return shape;
    }
    //鼠标左键
    identifyQueryHandler.setInputAction(function(event) {
        var earthPosition = getPickPositionGlobe(event.position);
        if (Cesium.defined(earthPosition)) {
            if (activeShapePoints.length === 0) {
                floatingPoint = createPoint(earthPosition);
                activeShapePoints.push(earthPosition);
                var dynamicPositions = new Cesium.CallbackProperty(function() {
                    if (drawingMode === 'polygon') {
                        return new Cesium.PolygonHierarchy(activeShapePoints);
                    }
                    return activeShapePoints;
                }, false);
                activeShape = drawShape(dynamicPositions); //绘制动态图
            }
            activeShapePoints.push(earthPosition);
            createPoint(earthPosition);
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    //鼠标移动
    identifyQueryHandler.setInputAction(function(event) {
        var position = event.endPosition;
        if (!Cesium.defined(position)) {
            return;
        }
        var num = activeShapePoints.length;
        if (num < 1) {
            tooltip.showAt(position, "<p>单击选择起点</p>");
            return;
        }
        tooltip.showAt(position, "<p>右击结束绘制</p>");
        if (Cesium.defined(floatingPoint)) {
            var newPosition = getPickPositionGlobe(event.endPosition);
            if (Cesium.defined(newPosition)) {
                floatingPoint.position.setValue(newPosition);
                activeShapePoints.pop();
                activeShapePoints.push(newPosition);
            }
        }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    function terminateShape() {
        activeShapePoints.pop(); //去除最后一个动态点
        if (activeShapePoints.length) {
            drawShape(activeShapePoints); //绘制最终图
        }
        viewer.entities.remove(floatingPoint); //去除动态点图形（当前鼠标点）
        viewer.entities.remove(activeShape); //去除动态图形
        floatingPoint = undefined;
        activeShape = undefined;
    }

    identifyQueryHandler.setInputAction(function(event) {
        var point1 = [activeShapePoints[0].x, activeShapePoints[0].y, activeShapePoints[0].z];
        var point2 = [activeShapePoints[1].x, activeShapePoints[1].y, activeShapePoints[1].z];
        var pointsArr = [point1, point2];
        pointsArr = mapProjectionToWGS84_2(pointsArr);
        terminateShape();

        var drawPoint1 = [pointsArr[0].longitude, pointsArr[0].latitude];
        var drawPoint2 = [pointsArr[1].longitude, pointsArr[0].latitude];
        var drawPoint3 = [pointsArr[1].longitude, pointsArr[1].latitude];
        var drawPoint4 = [pointsArr[0].longitude, pointsArr[1].latitude];
        pointsArr = [drawPoint1, drawPoint2, drawPoint3, drawPoint4, drawPoint1];
        var points = pointArrsToStringForQuery(pointsArr);
        removeAllEntities();
        queryLayerInfoByPoint(points, 3);

        //清空handler
        identifyQueryHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
        identifyQueryHandler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
        identifyQueryHandler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK);
        tooltip.setVisible(false);
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
}

function identifyClear() {
    if (identifyQueryHandler) {
        identifyQueryHandler.destroy();
        identifyQueryHandler = null;
    }
}